package refund

import java.math.BigDecimal

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.serializer.SerializerFeature
import com.alipay.api.domain.AlipayTradeRefundModel
import com.alipay.api.request.AlipayTradeRefundRequest
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.factory.InitializingBean
import org.springframework.stereotype.Service

@Service
class AliPayRefundAction extends BaseRefundAction with InitializingBean{

  override def getPayChannel: Integer = PayChannelEnum.ALI_PAY.getId

  @throws[Exception]
  override def refund[T <: RefundOrderReqDTO, R >: RefundOrderRespDTO](req: T): R = {
    val refundRequest = new AlipayTradeRefundRequest
    val tradeRefundModel = new AlipayTradeRefundModel
    tradeRefundModel.setOutTradeNo(req.getOriPayOrderNo)
    tradeRefundModel.setOutRequestNo(req.getPayRefundOrderNo)
    var bigDecimal = new BigDecimal(String.valueOf(req.getRefundAmount))
    bigDecimal = bigDecimal.divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP)
    tradeRefundModel.setRefundAmount(bigDecimal.toPlainString)
    refundRequest.setBizModel(tradeRefundModel)
    log.info("alipay refund request params : {}", JSON.toJSONString(refundRequest, SerializerFeature.PrettyFormat))
    val refundResponse = alipayClient.execute(refundRequest)
    log.info("alipay refund response result : {}", JSON.toJSONString(refundResponse, SerializerFeature.PrettyFormat))
    val resp = new RefundOrderRespDTO
    //BeanUtils.copyProperties(req, resp);
    resp.setPayChannel(req.getPayChannel)
    resp.setAmount(req.getRefundAmount)
    resp.setPayOrderNo(req.getPayRefundOrderNo)
    resp.setBizOrderNo(req.getBizRefundOrderNo)
    resp.setBizCode(if (StringUtils.isNotBlank(req.getBizCode)) req.getBizCode else PayEnum.BizCodeEnum.TRJ_APP_2019.getCode)
    resp.setUserId(req.getUserId)
    if (!refundResponse.isSuccess) {
      resp.setOrderStatusCode(ThirdSystemErrorEnum.getErrorEnum(refundResponse.getSubCode).getCode)
      resp.setOrderStatusMessage(ThirdSystemErrorEnum.getErrorEnum(refundResponse.getSubCode).getMessage)
    }
    else {
      resp.setOrderStatusCode(PayEnum.RefundTradeStatusEnum.getByThirdCode(refundResponse.getMsg, req.getPayChannel).getCode)
      resp.setOrderStatusMessage(PayEnum.RefundTradeStatusEnum.getByThirdCode(refundResponse.getMsg, req.getPayChannel).getDesc)
    }
    resp
  }

  override def afterPropertiesSet(): Unit = ActionFactory.setRefundAction(getPayChannel, this)
}
